<template>
  <div v-loading="loading" class="container">
    <el-tabs v-model="activeName" style="padding-left:30px">
      <!-- 基本信息 -->
      <el-tab-pane label="信息配置" name="first">
        <div class="section">
          <h2 class="title">基本信息</h2>
          <ul class="info">
            <li class="list-item">
              <div class="tip">
                <span class="must">*</span> 礼包名称：
              </div>
              <div class="detail">
                <el-input v-model="form.name" :maxlength="42" placeholder="请输入内容" />
              </div>
            </li>
            <li class="list-item">
              <div class="tip">
                <span class="must">*</span> 原价：
              </div>
              <div class="detail">
                <el-input v-model="form.yprice" :maxlength="42" placeholder="请输入内容" />
              </div>
              <!---->
              <div class="tip">
                <span class="must">*</span> 售价：
              </div>
              <div class="detail">
                <el-input v-model="form.price" :maxlength="42" placeholder="请输入内容" />
              </div>
            </li>
            <li class="list-item">
              <div class="tip">
                <span class="must">*</span> 邮费：
              </div>
              <div class="detail">
                <el-input v-model="form.freight" :maxlength="42" placeholder="请输入内容" />
              </div>
              <!---->
              <div class="tip">
                <span class="must">*</span> 销量：
              </div>
              <div class="detail">
                <el-input v-model="form.sales" :maxlength="42" placeholder="请输入内容" />
              </div>
            </li>
            <li class="list-item">
              <div class="tip">
                <span class="must">*</span> 关键词：
              </div>
              <div class="detail">
                <div class="detail">
                  <el-select
                    multiple
                    v-model="form.keyIds"
                    placeholder="请选择"
                    clearable
                    :key = "page_status"
                    @change="page"
                  >
                    <el-option
                      v-for="item in keyList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </div>
              </div>
              <!---->
              <div class="tip">
                <span class="must">*</span> 省份：
              </div>
              <div class="detail">
                <el-select v-model="form.provinceId" placeholder="请选择">
                  <el-option
                    v-for="item in addressOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </div>
            </li>
            <li class="list-item">
              <div class="tip">
                <span class="must">*</span> 排序：
              </div>
              <div class="detail">
                <el-input-number
                  v-model="form.sortWidget"
                  :precision="0"
                  :step="1"
                  size="medium"
                  :min="0"
                />
              </div>
            </li>
          </ul>

          <h2 class="title">礼包内容</h2>
          <ul class="info">
            <li class="list-item">
              <div class="tip">
                <span class="must">*</span> 礼包内容：
              </div>
              <div class="detail">
                <el-select v-model="form.comboType" placeholder="请选择">
                  <el-option
                    v-for="item in comboType_arr"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </li>
            <li class="list-item" v-if="form.comboType == 1">
              <div class="tip">
                <span class="must">*</span> 关联优惠券：
              </div>
              <div class="detail">
                <el-select
                  multiple
                  v-model="form.ticketsList"
                  filterable
                  placeholder="请选择"
                  @change="checkTicket"
                  remote
                  :remote-method="remoteMethod"
                  clearable
                  @blur="inputBlur"
                >
                  <el-option
                    v-for="item in ticket_list"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </li>
            <li class="list-item" v-if="form.comboType == 1">
              <div class="tip">
                <span class="must">*</span> 购买规则设置：
              </div>
              <div class="detail">
                <div class="rule">
                  <el-input v-model="form.ticketsList.length" :maxlength="20"  :disabled="true"/>
                  <span style="margin: auto 10px">选</span>
                  <el-input v-model="form.ticketCanUse" :maxlength="20"  />
                </div>
              </div>
            </li >
          </ul>
        </div>
        <div class="sub-btn">
          <el-button type="primary" @click="next_goods()">下一页</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="礼包材料配置" name="second">
        <div class="section">
          <h2 class="title">图片和详情</h2>
          <ul class="info">
            <li class="list-item">
              <div class="tip">
                <span class="must">*</span> 主图：
                <!--                <div class="msk">图片尺寸:1:1 推荐（355px*355px）</div>-->
              </div>
              <div class="detail project_detail">
                <ul class="img-list">
                  <li v-for="(item, index) in img_main_list" :key="index" class="img-item">
                    <img v-if="item.url" :src="item.url" alt class="img" />
                    <div class="del-btn" @click.stop="del_main(item)">
                      <i class="el-icon-delete" />
                    </div>
                  </li>
                </ul>
                <div class="upload-btn">
                  <el-upload
                    action="https://mpingweb.yuepinyuemei.com/api/upload"
                    :data="{
                  dirPath: 'authentication',
                  upload_status: true }"
                    :multiple="false"
                    :file-list="img_main_list"
                    :show-file-list="false"
                    list-type="picture-card"
                    :on-success="upload_main"
                    :before-upload="before_main"
                    :on-remove="del_main"
                  >
                    <i class="el-icon-plus icon" />
                  </el-upload>
                </div>
              </div>
            </li>
            <li class="list-item">
              <div class="tip">
                <span class="must">*</span>展示图：
                <div class="msk">图片尺寸:1:1</div>
              </div>
              <div class="detail project_detail">
                <ul class="img-list">
                  <li v-for="(item, index) in img_list" :key="index" class="img-item">
                    <img v-if="item.url" :src="item.url" alt class="img" />
                    <div class="del-btn" @click.stop="del_arr(item)">
                      <i class="el-icon-delete" />
                    </div>
                  </li>
                </ul>
                <div class="upload-btn">
                  <el-upload
                    action="https://mpingweb.yuepinyuemei.com/api/upload"
                    :data="{
                  dirPath: 'authentication',
                  upload_status: true }"
                    :multiple="true"
                    :limit="5"
                    :file-list="img_list"
                    :show-file-list="false"
                    list-type="picture-card"
                    :on-success="upload_arr"
                    :before-upload="before_main"
                    :on-remove="del_arr"
                  >
                    <i class="el-icon-plus icon" />
                  </el-upload>
                </div>
              </div>
            </li>
            <li class="list-item">
              <div class="tip">
                <span class="must">*</span> 礼包详情：
              </div>
              <div class="detail project_detail">
                <tinymce :id="tinymceId" v-model="form.des" :min-height="750" :width="760" />
              </div>
            </li>
          </ul>
        </div>
        <div class="sub-btn">
          <el-button type="primary" @click="save_goods()">保存</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import tinymce from "@/components/Tinymce";
import { addGoods, goodsTicketList, updateGoods,goodsDetail } from '../../api/goods'
import { provinceList } from '../../api/province'
import { keyWordDrop } from '../../api/keyWord'

export default {
  components: {
    tinymce,
  },
  data() {
    return {
      form: {
        id:undefined,//
        name: "", // 名称
        yprice: "", // 展示价
        price: "", // 售价
        freight: 0, // 邮费
        sales: 0, // 销量
        sortWidget: 1, // 排序
        des: "", // 详情
       	comboType: "", //	套餐类型 0商品套餐 1优惠券套餐
        tickets: null, //
        ticketsList: [], //	优惠券列表列表
        ticketCanUse: null, //	优惠券可使用数量
        ticketNum: null, //	优惠券可选总数
        slaveImageList:[], //轮播图列表
        coverImage:"",//   主图
        provinceId:"",//省份
        keyIds:[],//关键词idList

      },
      img_main_list: [],
      img_list: [],
      tinymceId: this.id || "vue-tinymce" + Date.parse(new Date()),
      activeName: "first",
      page_status: 1, //   页面状态  1 添加  2 编辑
      comboType_arr:[
        { value: 0, label: '默认' },
        { value: 1, label: '优惠券' },
      ],//
      ticket_list: [], //卡券下拉列表
      addressOptions:[], //省份下拉列表
      keyList:[], //关键词下拉列表
      key_arr: [], //关键词下拉列表 -搜索结果
      ticket_arr: [], //卡券下拉列表 -搜索结果
      ticket_id: "", //卡券
      goodsInfo: null,
      loading: false,
      couponHidden:true,//套餐类型为默认时  配置优惠券隐藏
    };
  },
  watch: {
    "form.coverImage"(val) {
      const arr = [
        {
          name: "main",
          url: this.common.img_url + val,
        },
      ];
      this.img_main_list = arr;
      this.$forceUpdate();
    },

    "form.slaveImageList"(val) {
      const arr = [];
      if (Array.isArray(val)) {
        val.forEach((item, index) => {
          arr.push({
            name: index,
            url: this.common.img_url + item,
          });
        });
        this.img_list = arr;
        this.$forceUpdate();
      }
    },
  },
  mounted() {
    // 页面状态  1 添加  2 编辑
    this.page_status = this.$route.query.page_status
    switch (this.$route.query.page_status) {
      case 1:
        this.$route.meta.title = "添加礼包";
        break;
      case 2:
        this.$route.meta.title = "编辑礼包";
        break;
      default:
        break;
    }
    if(this.page_status == 2){
      this.goods_detail(this.$route.query.id)

    }
    this.goodsTicketList();
    this.get_province();
    this.get_key();
  },
  methods: {
    // 上传主图
    upload_main(res) {
      this.loading = false;
      this.form.coverImage = res.data;
      this.$forceUpdate();
    },
    // 上传主图之前钩子
    before_main() {
      this.loading = true;
    },
    // 删除主图
    del_main(val) {
      this.form.coverImage = "";
      this.img_main_list =[]
    },
    // 上传展示图
    upload_arr(res) {
      this.loading = false;
      const arr = [...this.form.slaveImageList];
      arr.push(res.data);
      this.form.slaveImageList = arr;
    },
    // 删除展示图
    del_arr(val) {
      const del_url = val.url.split(this.common.img_url)[1];
      this.form.slaveImageList.forEach((item, index) => {
        if (del_url === item) {
          this.form.slaveImageList.splice(index, 1);
        }
      });
    },


    //
    page(e){
      this.form.keyIds =e
    },
    //获取商品详情
    goods_detail(e){
      goodsDetail({id:e}).then((res) => {
        if(res.data.code == 0){
          let  list = res.data.data
          this.form = list
          this.form.ticketsList= list.ticketsList == null ? [] : list.ticketsList //	优惠券列表列表
          this.$set(this.form,"keyIds",list.keywordIds);

        }else {
          this.$message.error(res.data.message);
        }
      }).catch((res) => {
        this.$message({
          showClose: true,
          message: res.data.message,
          type: "error",
        });
      });
    },

    //卡券下拉列表
    goodsTicketList() {
      goodsTicketList({
        // keyword: 1,
      })
        .then((result) => {
          const res = result.data;
          if (res.code === 200) {
            const arr = [];
            res.data.forEach((item) => {
              arr.push({
                value: item.id,
                label: item.type_name,
              });
            });
            this.ticket_arr = arr;
            this.ticket_list = arr;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    //获取省份下拉列表
    get_province(){
      provinceList({}).then(res => {
        this.addressOptions = res.data.data.list // 将获取的省份option 赋值 addressOptions
      }).catch(res => {
        this.$message.error('网络连接错误，请稍后再试')
      })
    },

    //关键词下拉列表
    get_key(){
      keyWordDrop({}).then(result => {
        const res = result.data;
        if (res.status === 0) {
          const arr = [];
          res.data.forEach((item) => {
            arr.push({
              id: item.id,
              name: item.name,
            });
          });
          this.key_arr = arr;
          this.keyList = arr;
        } else {
          this.$message.error(res.msg);
        }

      }).catch(res => {
        this.$message.error('网络连接错误，请稍后再试')
      })
    },


    // 下拉数据获取id
    handleChange(e) {
      this.form.hospital_id = e;
    },
    // 远程搜索获取机构名称
    remoteMethod(query) {
      const data = { keyword: query };
      if (query != "") {
        goodsTicketList(data)
          .then((result) => {
            const res = result.data;
            if (res.code === 200) {
              const arr = [];
              res.data.forEach((item) => {
                arr.push({
                  value: item.id,
                  label: item.type_name,
                });
              });
              this.ticket_list = arr;
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch((err) => {
            this.$message.error(err);
          });
      } else {
        this.ticket_list = this.ticket_arr;
      }
    },
    // 机构名称失焦
    inputBlur() {
      this.ticket_list = this.ticket_arr;
    },

    //套餐类型改变
    checkTicket(e){
      this.form.ticketNum = e.length+'';
    },

    next_goods() {
      if (this.form.name === "") {
        this.$message.error("请输入礼包名称");
      } else if (this.form.yprice === "") {
        this.$message.error("请输入原价");
      } else if (this.form.price === "") {
        this.$message.error("请输入售价");
        // } else if (this.form.freight === "") {
        //   this.$message.error("请输入邮费");
        // } else if (this.form.sales === "") {
        //   this.$message.error("请输入销量");
      // } else if (this.form.keyIds .length == 0 ) {
      //   this.$message.error("请选择关键字");
      } else if (this.form.provinceId == "") {
        this.$message.error("请选择省份");
        // } else if (this.form.sortWidget === "") {
        //   this.$message.error("请输入排序");
      } else if (this.form.comboType === "") {
        this.$message.error("请输入套餐类型");
      } else if (this.form.comboType == 1) {
        if (this.form.ticketsList.length === 0) {
          this.$message.error("请选择关联优惠券");
        }else if (this.form.ticketNum === null) {
          this.$message.error("请输入优惠券可选总数");
        }else if (this.form.ticketCanUse === null) {
          this.$message.error("请输入优惠券可使用数量");
        }else if(this.form.ticketCanUse - 0 > this.form.ticketNum - 0) {
          this.$message.error("输入优惠券可选总数必须大于优惠券可使用数量，eg:8选3");
        }else {
          this.activeName = "second";
        }
      }else{
        this.activeName = "second";
      }
    },
    // 保存
    save_goods() {
      if (this.form.name === "") {
        this.$message.error("请输入礼包名称");
      } else if (this.form.yprice === "") {
        this.$message.error("请输入原价");
      } else if (this.form.price === "") {
        this.$message.error("请输入售价");
        // } else if (this.form.freight === "") {
        //   this.$message.error("请输入邮费");
        // } else if (this.form.sales === "") {
        //   this.$message.error("请输入销量");
      // } else if (this.form.keyIds .length == 0 ) {
      //   this.$message.error("请选择关键字");
      } else if (this.form.provinceId  == "") {
        this.$message.error("请选择省份");
        // } else if (this.form.sortWidget === "") {
        //   this.$message.error("请输入排序");
      } else if (this.form.comboType === "") {
        this.$message.error("请输入套餐类型");
      } else
        if (this.form.comboType == 1 && this.form.ticketsList.length === 0 ) {
          this.$message.error("请选择关联优惠券");
        }else if (this.form.comboType == 1 && this.form.ticketNum === null) {
          this.$message.error("请输入优惠券可选总数");
        }else if (this.form.comboType == 1 && this.form.ticketCanUse === null) {
          this.$message.error("请输入优惠券可使用数量");
        }else if( this.form.comboType == 1 && this.form.ticketCanUse - 0 > this.form.ticketNum - 0) {
          this.$message.error("输入优惠券可选总数必须大于优惠券可使用数量，eg:8选3");
       } else if (this.form.coverImage === "") {
        this.$message.error("请上传主图");
      } else if (this.form.slaveImageList.length === 0) {
        this.$message.error("请上传展示图");
      } else if (this.form.des === "") {
        this.$message.error("请上传礼包详情");
      } else {

        switch (+this.page_status) {
          case 1:
            this.add_goods(this.form);
            break;
          case 2:
            this.rewrite_goods(this.form);
            break;

          default:
            break;
        }
      }
    },
    // 添加礼包
    add_goods(e) {
      this.form.ticketNum = this.form.ticketNum === "" ? null : this.form.ticketNum
      this.form.ticketCanUse = this.form.ticketCanUse === "" ? null : this.form.ticketCanUse
      this.form.tickets = this.form.tickets === "" ? null : this.form.tickets
      this.form.ticketsList = this.form.ticketsList === "" ? [] : this.form.ticketsList
      addGoods(e) .then((res) => {
        if (res.data.code === 7001) {
          this.$message.error(res.data.msg);
        } else {
          this.$message({
            showClose: true,
            message: "添加" + res.data.msg,
            type: "success",
          });
          this.$router.go(-1);
        }
      })
        .catch((res) => {
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "error",
          });
        });
    },
    // 编辑礼包
    rewrite_goods(e) {
      this.form.keywordIds = undefined
      this.form.ticketNum = this.form.ticketNum === "" ? null : this.form.ticketNum
      this.form.ticketCanUse = this.form.ticketCanUse === "" ? null : this.form.ticketCanUse
      this.form.tickets = this.form.tickets === "" ? null : this.form.tickets
      this.form.ticketsList = this.form.ticketsList === "" ? [] : this.form.ticketsList
      updateGoods(e).then((res) => {
          if (res.data.code === 7001) {
            this.$message.error(res.data.msg);
          } else {
            this.$message({
              showClose: true,
              message: "修改" + res.data.msg,
              type: "success",
            });
            this.$router.go(-1);
          }
        })
        .catch((res) => {
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "error",
          });
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.container {
  padding: 30px;
  .section {
    .title {
      width: 130px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      margin-bottom: 20px;
    }
    .info {
      margin-left: 40px;
      .list-item {
        margin-bottom: 20px;
        .tip {
          font-size: 14px;
          display: inline-block;
          vertical-align: middle;
          width: 150px;
          text-align: right;
          .msk {
            font-size: 10px;
            color: #666;
            margin-right: 20px;
            margin-top: 10px;
          }
          .must {
            display: inline-block;
            vertical-align: middle;
            color: #ff3040;
          }
        }
        .detail {
          color: #666;
          min-width: 350px;
          font-size: 16px;
          display: inline-block;
          vertical-align: middle;
          .el-select {
            display: block !important;
          }
          .img-list {
            display: inline-block;
            vertical-align: middle;
            .img-item {
              width: 150px;
              height: 150px;
              border: 1px solid #ccc;
              display: inline-block;
              vertical-align: middle;
              overflow: hidden;
              margin-right: 10px;
              position: relative;
              .img {
                width: 100%;
              }
              .del-btn {
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.3);
                color: #fff;
                line-height: 150px;
                text-align: center;
                font-size: 40px;
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                cursor: pointer;
                display: none;
              }
              &:hover {
                .del-btn {
                  display: block;
                }
              }
            }
          }
          .upload-btn {
            width: 150px;
            height: 150px;
            display: inline-block;
            vertical-align: middle;
            position: relative;
            .el-icon-plus {
              width: 150px;
              height: 150px;
              display: block;
              position: relative;
              &::before {
                font-size: 30px;
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
              }
            }
          }
          &.project_detail {
            vertical-align: top;
          }

          .rule {
            display: flex;
            align-items: center;
            justify-content: space-around;
            flex-direction: row;
          }
        }
      }
    }
  }
  .sub-btn {
    .el-button {
      margin: 80px auto 20px auto;
      display: block;
    }
  }

  .form-control {
    width: 100%;
    padding-right: 6px;
    min-height: 300px;
    -webkit-overflow-scrolling: touch;
    resize: none;
    outline: 0 none;
    margin-top: 12px;
    font-size: 14px;
    /*font-family: MicrosoftYaHei;*/
    color: rgba(13, 20, 30, 1);
    line-height: 19px;
    opacity: 0.6;
  }
}
</style>

